import pandas as pd
import datetime
import json
import os
from openpyxl import load_workbook


def export_to_excel(result, xlsx_name: str, columns_dict=None, sheet_name=None, index=False, save_path=None) -> str:
    if not save_path:
        save_path = f'res/{datetime.date.today()}-{xlsx_name}.xlsx'
    if not os.path.exists(save_path):
        xlsx = pd.ExcelWriter(save_path)
    else:
        book = load_workbook(save_path)
        xlsx = pd.ExcelWriter(save_path, engine='openpyxl')
        xlsx.book = book
    if isinstance(result, pd.DataFrame):
        df = result
    else:
        df = pd.DataFrame(result)
    if columns_dict:
        df = df.rename(columns=columns_dict)
    sheet_name = 'TEST' if sheet_name is None else sheet_name
    try:
        df.to_excel(xlsx, sheet_name=sheet_name, index=index)
    except Exception as e:
        print(e)
    xlsx.close()
    return save_path


def export_to_json(result: dict, json_name: str):
    res = json.dumps(result)
    with open(f'res/{json_name}.json', 'w+') as f:
        f.write(res)
